<?php

namespace App\Repositories;

use App\Models\Topic;
use App\Models\Comment;
use Illuminate\Http\Request;

class TopicRepository
{
    public function createTopic(Request $request)
    {
        $topic = \DB::transaction(function () use ($request) {
            $user = \Auth::user();
            $topic = $user->topics()->create([
                'type' => $request->get('type'),
            ]);
            $comment = $topic->comments()->create([
                'uid' => $topic->uid,
                'floor_num' => 1,
                'content' => $request->get('content'),
                'images' => json_encode($request->get('images', [])),
            ]);
            $applyJob = $request->apply_job;
            if ($topic->type == Topic::TYPE_APPLY_JOB && $applyJob)
            {
                $applyJob['uid'] = $topic->uid;
                $comment->applyJob()->create($applyJob);
            }
            return $topic;
        });

        return $topic;
    }

    public function createComment(Request $request)
    {
        $comment = \DB::transaction(function () use ($request) {
            $user = \Auth::user();
            $topic = Topic::findOrFail($request->get('tid'));
            $firstComment = $topic->firstComment()->firstOrFail();
            $pid = $request->get('pid', 0);
            $parent = null;
            if ($pid)
            {
                $parent = Comment::findOrFail($pid);
            }
            $comment = $topic->comments()->create([
                'uid' => $user->id,
                'content' => $request->get('content'),
                'pid' => $pid,
            ]);
            if ($pid)
            {
                if ($parent->target_type != $comment->target_type || $parent->target_id != $comment->target_id)
                {
                    throw new \LogicException("父评论 $pid 与子评论类型不一致");
                }
            }
            //更新评论楼层号
            $floorNum = $topic->comments()->where('pid', 0)->where('id', '<=', $comment->id)->withTrashed()->count();
            $comment->floor_num = $floorNum;
            $comment->save();

            //更新帖子回复数，帖子的数据以一楼的为准
            $replyCount = $topic->comments()->withTrashed()->count();
            $firstComment->reply_count = $replyCount - 1;
            $firstComment->save();

            return $comment;
        });

        return $comment;
    }

    public function createLike(Request $request)
    {
        $like = \DB::transaction(function () use ($request) {
            $user = \Auth::user();
            $comment = Comment::findOrFail($request->cid);
            $like = $comment->likes()->create([
                'uid' => $user->id,
            ]);
            $comment->like_count = $comment->likes()->count();
            $comment->save();
            return $like;
        });

        return $like;
    }
}